package com.offcn.order.controller;

import com.offcn.entity.Result;
import com.offcn.entity.StatusCode;
import com.offcn.order.entity.Cart;
import com.offcn.order.service.CartService;
import com.offcn.utils.TokenDecode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private TokenDecode tokenDecode;

    @Autowired
    private CartService cartService;

    @RequestMapping("/findCartList")
    public List<Cart> findCartList(){
        Map<String, String> getinfo =
                tokenDecode.getinfo();
        String username = getinfo.get("username");
        return cartService.findFromRedis(username);
    }

    @RequestMapping("/addToCart")
    public Result addToCart(Long itemId,Integer num){
        Map<String, String> getinfo =
                tokenDecode.getinfo();
        String username = getinfo.get("username");
        try {
            List<Cart> cartList = findCartList();
            cartList = cartService.addToCart(cartList,itemId,num);
            cartService.saveToRedis(username,cartList);
            return new Result(true, StatusCode.OK,"成功添加购物车！");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"添加失败！");
        }
    }
}


